var express = require('express');
const fs = require('fs');
const musr = require('./users');
const cman = require("../wssserv");
var router = express.Router();

function parseParams(data){
    const params = {};
    data.split("&").forEach((item) => {
        const kv = item.split("=");
        params[kv[0]] = kv[1];
    });
    return params;
}

router.post('/pubcheck', function (req, res, next) {
    const params = parseParams(req.body["params"]);
    if("id" in params && "key" in params && cman.check_key(params["id"],params["key"])){
        res.send({"code": 0, err:""});
    }else{
        res.send({"code": -1, "err": "Invliad ID & key."});
    }
});

router.post('/playcheck', function (req, res, next) {
    const params = parseParams(req.body["params"]);
    if("token" in params && musr.checkSessionID(params["token"])){
        res.send({"code": 0, "err": ""});
    }else{
        res.send({"code": -1, "err": "Invalid token."});
    }
});

router.post('/reqpush', function(req,res,next){
    const params = parseParams(req.body["params"]);
    if("token" in params && musr.checkSessionID(params["token"])){
        if(cman.ask_push(req.body.stream)){
            res.send({"code": 0, "err": ""});
        }else{
            console.log(`Pusher '${req.body.stream}' is not online. Fail to require pushing.`);
            res.send({"code": 1, "err": "Client not online"})
        }
    }else{
        res.send({"code": -1, "err": "Invalid token."});
    }
});

router.post('/reqstop', function(req,res,next){
    const params = parseParams(req.body["params"]);
    if("token" in params && musr.checkSessionID(params["token"])){
        if(cman.ask_stop(req.body.stream)){
            res.send({"code": 0, "err": ""});
        }else{
            console.log(`Pusher '${req.body.stream}' is not online. Fail to require stoping.`);
            res.send({"code": 1, "err": "Client not online"})
        }
    }else{
        res.send({"code": -1, "err": "Invalid token."});
    }
});

router.use((req, res, next) => {
    if (musr.isLogined(req)) {
        next();
    } else {
        res.send({ "success": false, "err": "NO_LOGIN" });
    }
});

CONFIG_FILE = __dirname + '/config.json';
AK_FILE = __dirname + '/ak.json';
var ak, channel, serverS, serverC;
function reloadConfig() {
    try {
        data = JSON.parse(fs.readFileSync(AK_FILE));
    } catch {
        ak = "";
        channel = "rabbit";
        serverS = "";
        serverC = "";
        return false;
    }
    try{
        channel = data["channel"];
    }catch{
        channel = "rabbit";
    }
    try {
        ak = data["ak"];
    } catch {
        ak = "";
    }
    try{
        serverS = data["serverS"];
    }catch{
        serverS = "https://127.0.0.1:443";
    }
    try{
        serverC = data["serverC"];
    }catch{
        serverC = "https://127.0.0.1:443";
    }
    return ak != "" && serverS != "" && serverC != "" && channel != "";
}
reloadConfig();
router.reloadConfig = reloadConfig;

function saveConfig() {
    try {
        fs.writeFileSync(AK_FILE, 
            JSON.stringify({
                "channel": channel,
                "ak": ak,
                "serverS": serverS,
                "serverC": serverC
            }));
        return true;
    } catch {
        return false;
    }
}
router.saveConfig = saveConfig;

router.get_ak = () => { return ak; }

router.get_channel = () => { return channel; }

router.get_serverS = () => { return serverS; }

router.get_serverC = () => { return serverC; }

router.get('/channels', function (req, res, next) {
    const channels = {};
    const pushers = cman.get_all_status();
    for(var pu in pushers) {
        channels[pu] = {"pushing": false} ;
    }
    fetch(`${serverS}/index/api/getMediaList?secret=${ak}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
        rejectUnauthorized: false
    }).then(response => response.json()).then(data => {
        if(data["code"]!=0){
            res.send({
                "success": false,
                "err": "bad_response: "+String(data["code"])+", "+data["msg"]
            });
            return;
        }
        if(data["data"]!=undefined){
            data.data.forEach((item) => {
                const ch = item["stream"];
                if(ch in channels){
                    channels[ch]["pushing"] = true;
                }else{
                    channels[ch] = {"pushing": true};
                }
            });
        }
        res.send({ "success": true, "data": channels });
    }).catch((error) => {
        res.send({ "success": false, "err": error });
    });
});

router.use((req, res, next) => {
    if (musr.isAdmin(req)) {
        next();
    } else {
        res.send({ "success": false, "err": "NOT_ADMIN" });
    }
});

router.post('/general', function (req, res, next) {
    if (req.body.ak != undefined) {
        ak = req.body.ak;
        channel = req.body.channel;
        serverS = req.body.serverS;
        serverC = req.body.serverC;
        res.send({ "success": saveConfig(), "err": "" });
    } else {
        res.send({ "success": false, "err": "empty" });
    }

});

function checkname(str){    
    // 判断字符串是否为数字和字母组合  
    var zg =  /^[0-9a-zA-Z]*$/;  
    if (str==="" || !zg.test(str))  {  
        return false;  
    } else {  
        return true;  
    }  
}

router.post("/addpusher", function (req, res, next) {
    const ID = req.body.id, KEY = req.body.key;
    if (ID != undefined && KEY != undefined && ID != "" && KEY != "") {
        if(checkname(ID) && checkname(KEY)){
            res.send({ "success": cman.add_client(ID, KEY), "err": "" });
        }else{
            res.send({ "success": false, "err": "not num and alpha" });
        }
    } else {
        res.send({ "success": false, "err": "empty" });
    }
});

router.post("/delpusher", function (req, res, next) {
    if (req.body.id != undefined) {
        res.send({ "success": cman.del_client(req.body.id), "err": "" });
    } else {
        res.send({ "success": false, "err": "empty" });
    }
});

router.post("/startpusher", function (req, res, next) {
    if (req.body.id != undefined) {
        res.send({ "success": cman.ask_push(req.body.id), "err": "Pusher not connected" });
    } else {
        res.send({ "success": false, "err": "empty" });
    }
});

router.post("/stoppusher", function (req, res, next) {
    if (req.body.id != undefined) {
        res.send({ "success": cman.ask_stop(req.body.id), "err": "Pusher not connected" });
    } else {
        res.send({ "success": false, "err": "empty" });
    }
});

module.exports = router;
